# coding:utf-8
# boto s3手册：http://boto.readthedocs.org/en/latest/ref/s3.html
# boto s3快速入门：http://boto.readthedocs.org/en/latest/s3_tut.html
# 如果脚本长时间阻塞，请检查集群状态，开启的端口等
import ssl
import boto.s3.connection
from boto.s3.key import Key

try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    pass
else:
    ssl._create_default_https_context = _create_unverified_https_context

# test用户的keys信息
access_key = "FYD5EAXWV69JM1IBSHO8"
secret_key = "LU0yUJUUKqJ6POosPDrm1f4poiFXPxgl5zihfomB"
# rgw的ip与端口
host = "192.168.10.50"
port = 443  # 如果使用443端口，下述链接应设置is_secure=True
#port = 80  # 如果使用80端口，下述链接应设置is_secure=False
conn = boto.connect_s3(
    aws_access_key_id=access_key,
    aws_secret_access_key=secret_key,
    host=host,
    port=port,
    is_secure=True,
    validate_certs=False,
    calling_format=boto.s3.connection.OrdinaryCallingFormat()
)


# 一：创建存储桶
conn.create_bucket(bucket_name='bucket01')
conn.create_bucket(bucket_name='bucket02')


# 二：获得一个存储桶
bucket1 = conn.get_bucket('bucket01')
bucket2 = conn.get_bucket('bucket02')
#
print("++++++++++++++++")
# 三：判断是否存在，不存在返回None
exists = conn.lookup('bucket01')
print(exists)
exists = conn.lookup('bucket02')
print(exists)

# 四：查看一个bucket下的内容
print(list(bucket1.list()))
print(list(bucket2.list()))

print("________________________")
'''
'''
# 五：向s3上存储数据, 数据来源可以是file、stream、or string
# 5.1、上传文件
bucket1 = conn.get_bucket('bucket01')
key = Key(bucket=bucket1, name='myfile')  # name的值是数据的key
key.set_contents_from_filename('test.txt')
print(key.get_contents_as_string())  # 读取s3中文件的内容，返回string即文件test.txt的内容

print("<======================>")
'''
'''
# 5.2、上传字符串
bucket1 = conn.get_bucket('bucket01')  # 如果之前已经获取过对象，此处不需要重复获取
k = Key(bucket1)
k.key = 'xxx'
k.set_contents_from_string('dyx is happy')
print(k.get_contents_as_string())
#

# 六：删除一个存储桶，在删除存储桶本身时必须删除该存储桶内的所有key
bucket1 = conn.get_bucket('bucket01')
for key in bucket1:
    key.delete()
bucket1.delete()

# bucket1.get_all_keys()[0].delete()  # 删除某一个key

# 迭代遍历buckets and keys
for bucket in conn:
    for key in bucket:
        print(key.name,key.get_contents_as_string())

# 一个判断文件夹中是否有文件的方法
bucket1 = conn.get_bucket('bucket01')
res = bucket1.get_all_keys()
if len(res) > 0:
    print('有文件')
else:
    print('为空')
